package com.pignest.hotel.schedule;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.pignest.framework.util.Log;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.definition.OpenRoomType;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Config;
import com.pignest.hotel.system.L;
import com.pignest.hotel.util.DateUtil;

public class LivingUpdateJob implements Job {

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		Log.v();
		ReceptionService service = Services.getReceptionService();
		List<Living> livings = service.listCurrentLivings();
		if (livings == null || livings.isEmpty())
			return;
		
		long now = System.currentTimeMillis();
		List<Living> u = new ArrayList<Living>();
		for (Living living : livings) {
			String openRoomType = living.getOpenRoomType();
			boolean changed = false;
			if (OpenRoomType.HOURS.is(openRoomType)) {
				if (now > living.getGrantDate().getTime()) {
					changed = true;
					living.setOpenRoomType(OpenRoomType.HALFDAY.name());
					long h = (Config.getHalfDayPeriod() - Config.getHourPeriod()) * DateUtil.ONE_HOUR;
					living.setGrantDate(new Date(living.getGrantDate().getTime() + h));
					living.setAdjustPrice(living.getRoom().getType().getHalfDayPrice());
				}
			} else if (OpenRoomType.HALFDAY.is(openRoomType)) {
				if (now > living.getGrantDate().getTime()) {
					changed = true;
					living.setOpenRoomType(OpenRoomType.DAY.name());
					living.setAdjustPrice(living.getRoom().getType().getPrice());
				}
//			} else if (OpenRoomType.DAY.is(openRoomType)) {
//				
			}
			if (changed)
				living.setOvertime(Living.OVERTIME_NO);
			if (!changed && living.updateOvertime(now))
				changed = true;
			if (changed)
				u.add(living);
		}
		if (!u.isEmpty()) {
			service.saveAll(u);
			L.update(u, "系统自动更新");
			Log.i();
		}
	}

}
